import json

from django.views import View
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from apps.users.serializers import *
from rest_framework.views import APIView
from libs.yuntongxun.sms import CCP
from django.contrib.auth import authenticate
from apps.users.utils import set_token


class SendSms_codeAPIView(APIView):
    """短信验证码"""

    def get(self, request, mobile):
        """发送短信验证码"""
        code = 123456
        redis_cli = get_redis_connection('default')
        redis_cli.setex(mobile, 300, code)
        # celery_send_sms_code.delay(mobile, code)
        CCP().send_template_sms(mobile, [code, 6], 1)

        return Response({'success': True,
                         'sms_code': code,
                         'message': '测试阶段验证码为%s' % code
                         })


class RegisterCreateView(CreateAPIView):
    """注册"""
    serializer_class = RegisterModelSerializer
    queryset = User



# 手机号登录
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class AuthenticateMobile(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get('mobile')
            username = User.objects.get(mobile=username).username
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            UserModel().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

class LoginAPIView(APIView):
    """登录"""

    def post(self, request):
        mobile = request.data.get('username')
        password = request.data.get('password')
        a = AuthenticateMobile()

        user = a.authenticate(request,mobile=mobile, password=password)

        if user is None:
            return Response({'msg': '账号或密码错误'}, status=400)
        token = set_token(user)
        return Response({'mobile': mobile,
                         'token': token,
                         'id': user.id,
                         'username': user.username,
                         'avatar': user.avatar})
